const request = require('request')
import { rejects } from "assert";
// src/controllers/auth.ts
import { Context } from "koa";
const AK = "dcTVGrcVPiOTsqx3ypoqVCRB"
const SK = "2Ke2An9LibC0xuXUCTYlXa5LB80a7nGp"


 async function idcardOcr(path:string) {
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        },
        // image 可以通过 getFileContentAsBase64("C:\fakepath\chengsf2.jpg") 方法获取,
        form: {
            'id_card_side': 'front',
            'image': getFileContentAsBase64(path),
            'detect_risk': 'false',
            'detect_quality': 'false',
            'detect_photo': 'false',
            'detect_card': 'false',
            'detect_direction': 'false'
        }
    };
    
    // const that = this;
   const res = await new Promise((resolve,reject)=>{
       request(options, function (error: any, response: any) {
           if (error) throw new Error(error);
           console.log(response.body);
           resolve(JSON.parse(response.body))
       });
   }) 
    console.log('res res' ,res);
    
    return { status:200,data: res} ;
    
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken () {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
        request(options, (error:any, response:any) => {
            if (error) { reject(error) }
            else { resolve(JSON.parse(response.body).access_token) }
        })
    })
}

/**
 * 获取文件base64编码
 * @param string  path 文件路径
 * @return string base64编码信息，不带文件头
 */
function getFileContentAsBase64 (path:string) {
    const fs = require('fs');
    try {
        return fs.readFileSync(path, { encoding: 'base64' });
    } catch (err) {
        throw new Error(err);
    }
}



// src/controllers/user.ts
// import { Context } from "koa";

export default class OCRfunction {
    public static async ocrupload(ctx: Context) {
        const files = ctx.request.body as any;
        // console.log('path1222', files.filepath)
        const res = await idcardOcr(files.filepath);
        ctx.body = res
    }
}

